package com.buka.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalFallback implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException ex) throws Exception {

        // 根据不同的异常类型返回对应的错误信息
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        if (ex instanceof FlowException) {
            response.getWriter().print("{\"code\": 429, \"message\": \"请求被限流，请稍后再试\"}");
        } else if (ex instanceof DegradeException) {
            response.getWriter().print("{\"code\": 503, \"message\": \"服务暂时不可用，请稍后再试\"}");
        } else if (ex instanceof ParamFlowException) {
            response.getWriter().print("{\"code\": 400, \"message\": \"参数限流，请检查参数\"}");
        } else if (ex instanceof SystemBlockException) {
            response.getWriter().print("{\"code\": 500, \"message\": \"系统负载过高，请稍后再试\"}");
        } else if (ex instanceof AuthorityException) {
            response.getWriter().print("{\"code\": 403, \"message\": \"没有权限访问\"}");
        }
    }
}
